/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Client;

import java.awt.BorderLayout;
import java.awt.HeadlessException;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowEvent;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.net.Socket;
import java.util.Vector;
import javax.swing.*;
import jsyntaxpane.DefaultSyntaxKit;

/**
 *
 * @author DUY
 */
public class ClientForm  extends JFrame implements ActionListener
{
   
   private javax.swing.JButton _jbtExecute;
    private javax.swing.JPanel _jpContainerTextAreaQuery;
    private javax.swing.JPanel _jpContent;
    private javax.swing.JEditorPane _jtaQuery;
    private javax.swing.JMenu jMenu1;
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JMenuItem jMenuFileExit;
    private javax.swing.JMenuItem jMenuFileConnect;
    private javax.swing.JMenuItem jMenuFileDisConnect;
    private javax.swing.JPanel jPanelTabResult;
    private javax.swing.JPanel jPanelTabHistory;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JSplitPane jSplitPane1;
    private javax.swing.JTabbedPane jTabbedPane1;
    private javax.swing.JList jListHistory;
    private DefaultListModel modelHistory ;
    private Socket clientSocket = null;
   private ObjectInputStream inputStream = null;   
   private Boolean isConnected = Boolean.FALSE;
    private JScrollPane jScrollPane1;
   
  
    public ClientForm()
    {   
        
        _jpContent = new javax.swing.JPanel();
        _jpContainerTextAreaQuery = new javax.swing.JPanel();
        jSplitPane1 = new javax.swing.JSplitPane();
        jPanel3 = new javax.swing.JPanel();
        jScrollPane2 = new javax.swing.JScrollPane();
        _jtaQuery = new javax.swing.JEditorPane();
        _jbtExecute = new javax.swing.JButton();
        jTabbedPane1 = new javax.swing.JTabbedPane();
        jPanelTabResult = new javax.swing.JPanel();
        jPanelTabHistory = new javax.swing.JPanel();
        jMenuBar1 = new javax.swing.JMenuBar();
        jMenu1 = new javax.swing.JMenu();
        jMenuFileDisConnect = new javax.swing.JMenuItem();
        jMenuFileConnect = new javax.swing.JMenuItem();
        jMenuFileExit = new javax.swing.JMenuItem();
        jListHistory = new JList();
        modelHistory = new DefaultListModel();
        jScrollPane1 = new JScrollPane();
        initComponents();
          Connect();
    }
    private void Exit() {

        int result = JOptionPane.showConfirmDialog(this, "Bạn chắc muốn thoát không?", "Client", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);

        if (result == JOptionPane.YES_OPTION) {
            
                
                System.exit(0);
            
        }
    }
    private void initComponents()
    {
      

        setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);
        setTitle("Client-Disconect");
        setBackground(new java.awt.Color(204, 204, 255));
        setMinimumSize(new java.awt.Dimension(898, 640));
         
        _jpContent.setBackground(new java.awt.Color(153, 153, 255));
        _jpContent.setMinimumSize(new java.awt.Dimension(888, 640));

        _jpContainerTextAreaQuery.setBackground(new java.awt.Color(204, 204, 255));
        _jpContainerTextAreaQuery.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));

        jSplitPane1.setOrientation(javax.swing.JSplitPane.VERTICAL_SPLIT);
        jSplitPane1.setPreferredSize(new java.awt.Dimension(500, 198));

        jPanel3.setMinimumSize(new java.awt.Dimension(851, 150));
        jPanel3.setPreferredSize(new java.awt.Dimension(851, 400));

        jScrollPane2.setMinimumSize(new java.awt.Dimension(23, 100));
        jScrollPane2.setPreferredSize(new java.awt.Dimension(146, 200));
  
        jScrollPane2.setViewportView(_jtaQuery);
               DefaultSyntaxKit.initKit();
//        _jtaQuery.setColumns(20);
        _jtaQuery.setFont(new java.awt.Font("Monospaced", 0, 12));
  //      _jtaQuery.setLineWrap(true);
        _jtaQuery.setContentType("text/sql");
       
        
        _jtaQuery.setMinimumSize(new java.awt.Dimension(104, 50));
        _jtaQuery.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                _jtaQueryKeyPressed(evt);
            }
        });
        _jbtExecute.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
        _jbtExecute.setText("Execute");
        _jbtExecute.addActionListener(this);

        javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
        jPanel3.setLayout(jPanel3Layout);
        jPanel3Layout.setHorizontalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addGap(369, 369, 369)
                .addComponent(_jbtExecute, javax.swing.GroupLayout.DEFAULT_SIZE, 102, Short.MAX_VALUE)
                .addGap(380, 380, 380))
            .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 851, Short.MAX_VALUE)
        );
        jPanel3Layout.setVerticalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel3Layout.createSequentialGroup()
                .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 144, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(_jbtExecute, javax.swing.GroupLayout.PREFERRED_SIZE, 34, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );

        jSplitPane1.setTopComponent(jPanel3);

        jTabbedPane1.setMinimumSize(new java.awt.Dimension(105, 150));


       
        jTabbedPane1.addTab("Result", jPanelTabResult);

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanelTabHistory);
        jPanelTabHistory.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 846, Short.MAX_VALUE)
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 304, Short.MAX_VALUE)
        );
        
        jTabbedPane1.addTab("History", jPanelTabHistory);
       
        jListHistory.setModel(modelHistory);
        jScrollPane1.setViewportView(jListHistory);
        jListHistory.addListSelectionListener(new javax.swing.event.ListSelectionListener() {
            public void valueChanged(javax.swing.event.ListSelectionEvent evt) {
                jListHistoryValueChanged(evt);
            }

           
        });
        jListHistory.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jListHistoryMouseClicked(evt);
            }
        });
        javax.swing.GroupLayout jPanelTabHistoryLayout = new javax.swing.GroupLayout(jPanelTabHistory);
        jPanelTabHistory.setLayout(jPanelTabHistoryLayout);
        jPanelTabHistoryLayout.setHorizontalGroup(
            jPanelTabHistoryLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 846, Short.MAX_VALUE)
        );
        jPanelTabHistoryLayout.setVerticalGroup(
            jPanelTabHistoryLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanelTabHistoryLayout.createSequentialGroup()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 343, Short.MAX_VALUE)
                .addContainerGap())
        );

        jSplitPane1.setBottomComponent(jTabbedPane1);

        javax.swing.GroupLayout _jpContainerTextAreaQueryLayout = new javax.swing.GroupLayout(_jpContainerTextAreaQuery);
        _jpContainerTextAreaQuery.setLayout(_jpContainerTextAreaQueryLayout);
        _jpContainerTextAreaQueryLayout.setHorizontalGroup(
            _jpContainerTextAreaQueryLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(_jpContainerTextAreaQueryLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jSplitPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 853, Short.MAX_VALUE)
                .addGap(10, 10, 10))
        );
        _jpContainerTextAreaQueryLayout.setVerticalGroup(
            _jpContainerTextAreaQueryLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, _jpContainerTextAreaQueryLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jSplitPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 539, Short.MAX_VALUE)
                .addContainerGap())
        );

        javax.swing.GroupLayout _jpContentLayout = new javax.swing.GroupLayout(_jpContent);
        _jpContent.setLayout(_jpContentLayout);
        _jpContentLayout.setHorizontalGroup(
            _jpContentLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(_jpContentLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(_jpContainerTextAreaQuery, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGap(10, 10, 10))
        );
        _jpContentLayout.setVerticalGroup(
            _jpContentLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, _jpContentLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(_jpContainerTextAreaQuery, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );

        jMenu1.setText("File");

        jMenuFileDisConnect.setText("Disconect");
        jMenuFileDisConnect.addActionListener(this);
        jMenuFileDisConnect.setVisible(false);
        jMenu1.add(jMenuFileDisConnect);

        jMenuFileConnect.setText("Connect");
        jMenuFileConnect.addActionListener(this);
        jMenu1.add(jMenuFileConnect);

        jMenuFileExit.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_X, java.awt.event.InputEvent.CTRL_MASK));
        jMenuFileExit.setText("Exit");
        jMenuFileExit.addActionListener(this);
        jMenu1.add(jMenuFileExit);

        jMenuBar1.add(jMenu1);

        setJMenuBar(jMenuBar1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(_jpContent, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(_jpContent, javax.swing.GroupLayout.PREFERRED_SIZE, 585, Short.MAX_VALUE)
        );
       
        pack();
        
       
        this.addWindowListener(new java.awt.event.WindowAdapter() {

            @Override
            public void windowClosing(WindowEvent winEvt) {
                Exit();
            }
            
                              
        });
       
        setVisible(Boolean.TRUE);
        
    }
    
    private void jListHistoryValueChanged(javax.swing.event.ListSelectionEvent evt) {
// TODO add your handling code here:
    _jtaQuery.setText(jListHistory.getSelectedValue().toString());
}
    private void jListHistoryMouseClicked(java.awt.event.MouseEvent evt) {
    _jtaQuery.setText(jListHistory.getSelectedValue().toString());
}
    private void _jtaQueryKeyPressed(java.awt.event.KeyEvent evt) {                                     
    if(evt.getKeyCode()== java.awt.event.KeyEvent.VK_F5)
    {
        Execute();
    }
} 
    @Override
    public void actionPerformed(ActionEvent e) {
        if (e.getSource() == jMenuFileExit) {
            Exit();
        }
        if (e.getSource() == _jbtExecute) {
            Execute();
        }
         if (e.getSource() == jMenuFileConnect) {
            Connect();
        }
         if (e.getSource() == jMenuFileDisConnect) {
            DisConnect();
        }
    }
    private void Connect()  
    {
        
        Boolean Continue = true;
        while (Continue) {
            try {
                Continue = false;
               
                 JTextField IpField = new JTextField();
                JTextField PortField = new JTextField();
               IpField.setText("127.0.0.1");
               PortField.setText("123");
                Object[] message = new Object[]{"IP SERVER:", IpField, "Port:", PortField};
                int r = JOptionPane.showConfirmDialog(this, message, "Connect", JOptionPane.OK_CANCEL_OPTION);
                if (r == JOptionPane.OK_OPTION) { 
                    
                    clientSocket = new Socket(IpField.getText(), Integer.parseInt(PortField.getText()));// Tao clinent socket de ket noi toi server
                   inputStream = new ObjectInputStream(clientSocket.getInputStream());
                    isConnected = Boolean.TRUE;
                    setTitle("Client-Conected");
                    jMenuFileConnect.setVisible(false);
                    jMenuFileDisConnect.setVisible(true);
                   
                }
            } catch (HeadlessException | NumberFormatException | IOException e)
            {

                int r = JOptionPane.showConfirmDialog(this, "Cannot connect to Server!Do you want to try again?", "CLient", JOptionPane.YES_NO_OPTION);
                if (r == JOptionPane.YES_OPTION)
                {
                    Continue = true;
                }
            }
        }
    }
   public void DisConnect()
   {
        try {
            clientSocket.close();
            clientSocket = null;
              isConnected = Boolean.FALSE;
               jMenuFileConnect.setVisible(true);
                    jMenuFileDisConnect.setVisible(false);
              setTitle("Client-Disconect");
        } catch (IOException ex) {
            ex.printStackTrace();
        }
   }
    public  void Execute()
    {
        if(isConnected == Boolean.TRUE)
        {
            modelHistory.addElement(_jtaQuery.getText());
             jTabbedPane1.setSelectedIndex(0);
        try {
            jPanelTabResult.removeAll();
             DataOutputStream sendToServer = null;
            
            
                JTable table = new JTable();
               
                   
                sendToServer = new DataOutputStream(clientSocket.getOutputStream());
                
                String Query = _jtaQuery.getText();
                Query= Query.replaceAll("\r\n", "");
                sendToServer.writeBytes(Query+"\n");
                String kq= (String)inputStream.readObject();
                String[] strings = kq.split("#");
                
                if ("thanh cong".equals(strings[1])) 
                {
                    if("select".equals(strings[0]))
                    {
                    Vector<String> colum = (Vector<String>) inputStream.readObject();

                    Object[][] dynamic = (Object[][]) inputStream.readObject();

                    table.setModel(new javax.swing.table.DefaultTableModel(
                            dynamic,
                            colum.toArray()) {

                        @Override
                        public boolean isCellEditable(int row, int column) {
                            //all cells false
                            return false;
                        }
                    });

                    // table.setPreferredScrollableViewportSize(new Dimension(800, 400));

                    table.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);

                    jPanelTabResult.setLayout(new BorderLayout());

                    jPanelTabResult.add(new JScrollPane(table));
                    }
                    else
                    {
                        JTextArea area = new JTextArea("execute query "+strings[0]+" success!");
                        jPanelTabResult.setLayout(new BorderLayout());


                        jPanelTabResult.add(new JScrollPane(area));
                    }
                    
                   
            } else {
                JTextArea area = new JTextArea("execute query "+strings[0]+" fail!");
                jPanelTabResult.setLayout(new BorderLayout());


                jPanelTabResult.add(new JScrollPane(area));
            }
            jPanelTabResult.updateUI();
          
        } catch (IOException | ClassNotFoundException ex) {
             System.out.print("error");
        }
        
        }
        else
        {
            int r = JOptionPane.showConfirmDialog(this, "Not connect to server!Do you want to Connect?", "CLient", JOptionPane.YES_NO_OPTION);
                if (r == JOptionPane.YES_OPTION)
                {
                    Connect();
                }
        }
    }

   
    public static void main(String args[]) {
        /*
         * Set the Nimbus look and feel
         */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /*
         * If Nimbus (introduced in Java SE 6) is not available, stay with the
         * default look and feel. For details see
         * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(ClientForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /*
         * Create and display the form
         */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new ClientForm();
                
            }
        });
    }
    
    
}
